package com.hqd.ch03.v46.web.servlet.view;

import com.hqd.ch03.v46.utils.StringUtils;
import com.hqd.ch03.v46.web.servlet.RequestToViewNameTranslator;
import com.hqd.ch03.v46.web.utils.ServletRequestPathUtils;

import javax.servlet.http.HttpServletRequest;


public class DefaultRequestToViewNameTranslator implements RequestToViewNameTranslator {

    private static final String SLASH = "/";
    /**
     * 前缀
     */
    private String prefix = "";
    /**
     * 后缀
     */
    private String suffix = "";
    /**
     * 分隔符
     */
    private String separator = SLASH;
    /**
     * 是否去除开头的/
     */
    private boolean stripLeadingSlash = true;
    /**
     * 是否去除结尾的/
     */
    private boolean stripTrailingSlash = true;
    /**
     * 是否去除拓展名
     */
    private boolean stripExtension = true;

    public void setPrefix(String prefix) {
        this.prefix = (prefix != null ? prefix : "");
    }

    public void setSuffix(String suffix) {
        this.suffix = (suffix != null ? suffix : "");
    }

    public void setSeparator(String separator) {
        this.separator = separator;
    }

    public void setStripLeadingSlash(boolean stripLeadingSlash) {
        this.stripLeadingSlash = stripLeadingSlash;
    }

    public void setStripTrailingSlash(boolean stripTrailingSlash) {
        this.stripTrailingSlash = stripTrailingSlash;
    }

    public void setStripExtension(boolean stripExtension) {
        this.stripExtension = stripExtension;
    }


    @Override
    public String getViewName(HttpServletRequest request) {
        String path = ServletRequestPathUtils.getCachedPath(request);
        return (this.prefix + transformPath(path) + this.suffix);
    }

    protected String transformPath(String lookupPath) {
        String path = lookupPath;
        if (this.stripLeadingSlash && path.startsWith(SLASH)) {
            path = path.substring(1);
        }
        if (this.stripTrailingSlash && path.endsWith(SLASH)) {
            path = path.substring(0, path.length() - 1);
        }
        if (this.stripExtension) {
            path = StringUtils.stripFilenameExtension(path);
        }
        if (!SLASH.equals(this.separator)) {
            path = StringUtils.replace(path, SLASH, this.separator);
        }
        return path;
    }
}